/**
 * Created with Vim7.3 Mac
 * @fileOverview : 
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-08-10 14:55:37
 * @filename : src/common/NetworkImg.js
 * @version : 
 * @description : 
 */


import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    ActivityIndicator
} from 'react-native';

let { width, height } = Utils.size;
let exitComponent = true;

class NetWorkImg extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loadSize: this.props.loadSize || 'small',
            loading: true,
            imgSize:this.props.imgSize,
            getSize:false,
            bw:null,
            bh:null,
        } 
    }

    componentDidMount() {
        exitComponent = true;
    }

    componentWillUnmount() {
        exitComponent = false;
    }

    getSize(bw,bh) {
        // imgSize={true}才会触发该函数计算
        let cw = width,
            ch = this.props.boxHeight;
        if (bw > cw || bh > ch) {
            if (bw/cw > bh/ch) { 
                bh = ch * (cw/bw);
                bw = bw < cw ? bw : cw;
            }  else {
                bw = cw * (ch/bh);
                bh = bh < ch ? bw : ch;
            }
        }
        return {bw:bw,bh:bh};
    }

    imgJSX() {
        let tthis=this,jsx,loader = this.state.loading ? <ActivityIndicator  size={this.state.loadSize}/> : null;   
        let imgStyle = this.state.getSize ? [styles.img,this.props.style,{width:this.state.bw,height:this.state.bh}] : [styles.img,this.props.style];
        if (this.state.imgSize) {
            jsx = <ActivityIndicator size={this.props.loadSize}/>;
            Image.getSize(this.props.source,function(bw,bh){
                let obj = tthis.getSize(bw,bh);
                console.log(69,exitComponent);
                if (exitComponent) {
                    tthis.setState({imgSize:false,getSize:true,bw:obj.bw,bh:obj.bh});
                }
            },function(e){console.log(e)})
        } else {
            jsx = <Image 
                    source={this.props.source}
                    style={imgStyle}
                    onLoadStart={(e) => {}}
                    onError={(e) => console.log(e.nativeEvent.error)}
                    onLoad={() => this.setState({loading: false})}>
                    {loader}
                  </Image>;

        }
        return (jsx)
    }

    render() {
        return this.imgJSX();
    }
}

const styles = StyleSheet.create({  
    img : {
        alignItems: 'center',
        justifyContent: 'center',  
    },
});

export default NetWorkImg;